package com.manner.groupon.service.groupon.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.manner.groupon.exception.CustomException;
import com.manner.groupon.mapper.DeductionCouponMapper;
import com.manner.groupon.mapper.UserMapper;
import com.manner.groupon.model.dto.deuctionCoupon.UserGetDeductionCouponVo;
import com.manner.groupon.model.entity.DeductionCoupon;
import com.manner.groupon.model.entity.User;
import com.manner.groupon.service.groupon.DeductionCouponService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

import static com.manner.groupon.constant.BusinessConstant.CONVERSION_MULTIPLIER;
import static com.manner.groupon.constant.DeductionCouponStatus.ALREADY_GIFTED;
import static com.manner.groupon.constant.DeductionCouponStatus.NOT_USED;


/**
 * @Author: Manner
 * @Description: 针对表[tb_deduction_coupon(抵扣券表)]的数据库操作Service实现
 * @DateTime: 2024/12/1 18:26
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class DeductionCouponServiceImpl extends ServiceImpl<DeductionCouponMapper, DeductionCoupon> implements DeductionCouponService {

    private final DeductionCouponMapper deductionCouponMapper;

    private final UserMapper userMapper;

    /**
     * @param shareUserPhone    分享赠送用户手机账号
     * @param receiveUserPhone  领取用户的手机账号
     * @param shareGiveCouponId 分享赠送的直减订单金额优惠券编号
     * @return BaseResponse
     * @description: 微信小程序分享转发给朋友, 赠送的直减订单金额的优惠券编号
     * @author Manner
     * @date 2024/12/2 15:09
     */
    @Override
    @Transactional(rollbackFor = Throwable.class)
    public String shareGiveGrouponCouponOrder(String shareUserPhone, String receiveUserPhone, Long shareGiveCouponId) {
        //先查询赠送的优惠券信息
        DeductionCoupon shareGiveDeductionCoupon = deductionCouponMapper.selectOne(new LambdaQueryWrapper<DeductionCoupon>()
                .eq(DeductionCoupon::getId, shareGiveCouponId)
                .eq(DeductionCoupon::getStatus, NOT_USED));

        if (BeanUtil.isEmpty(shareGiveDeductionCoupon)) {
            throw new CustomException("转赠的优惠券:" + shareGiveDeductionCoupon.getId() + ",不存在或者已被别的用户领取");
        }

        //更新转态为已转赠
        shareGiveDeductionCoupon.setStatus(ALREADY_GIFTED);
        //更新数据库记录行
        deductionCouponMapper.updateById(shareGiveDeductionCoupon);

        //查询领取人的个人信息
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getPhone, receiveUserPhone));

        if (BeanUtil.isEmpty(user)) {
            throw new CustomException("领取优惠券的用户不存在!");
        }

        DeductionCoupon receiveDeductionInfo = DeductionCoupon.builder()
                .userId(user.getId())
                .title("好友赠送" + shareGiveDeductionCoupon.getAmountScore() / CONVERSION_MULTIPLIER + "元优惠券")
                .amount(shareGiveDeductionCoupon.getAmount())
                .amountScore(shareGiveDeductionCoupon.getAmountScore())
                .effectiveDays(shareGiveDeductionCoupon.getEffectiveDays())
                .status(NOT_USED)
                .description(shareGiveDeductionCoupon.getDescription())
                .giveUserPhone(shareUserPhone)
                .expirationDateText(shareGiveDeductionCoupon.getExpirationDateText())
                .build();

        deductionCouponMapper.insert(receiveDeductionInfo);
        return "好友分享赠送的优惠券已到账!";
    }

    /**
     * @param phone
     * @return List<DeductionCoupon>
     * @description: 获取当前登录用户的所有满减抵扣优惠券信息
     * @author Manner
     * @date 2024/12/1 23:34
     */
    @Override
    public List<UserGetDeductionCouponVo> getMyAllDeductionCoupon(String phone) {
        //用户信息
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getPhone, phone));
        //用户名下的所有可用优惠券信息
        List<DeductionCoupon> deductionCoupons = deductionCouponMapper.selectList(new LambdaQueryWrapper<DeductionCoupon>()
                .eq(DeductionCoupon::getUserId, user.getId())
                .eq(DeductionCoupon::getStatus, NOT_USED)
        );
        //准备过滤数据的容器
        List<UserGetDeductionCouponVo> userGetDeductionCouponVos = new ArrayList<>();
        //开始过滤构建数据
        deductionCoupons.stream().forEach(deductionCoupon -> {
            userGetDeductionCouponVos.add(BeanUtil.copyProperties(deductionCoupon, UserGetDeductionCouponVo.class));
        });
        return userGetDeductionCouponVos;
    }
}
